<?php

namespace Api\Member\AuthManager\Self;

use Api\RepositoryResourceTrait;
use Illuminate\Support\Facades\DB;

class ManagerRepository
{
    use RepositoryResourceTrait;

    /**
     * 允许列表查询的每页最大条目
     *
     * @var int
     */
    private $allowMaxPerPage = 100;

    /**
     * 可见字段
     *
     * @var array
     */
    private $visible = [
        'id',
        'account',
        'country_code',
        'mobile',
        'last_ip',
        'status',
        'roles',
        'auth_fail_num',
        'confine_time',
        'created_at',
        'updated_at'
    ];

    /**
     * 构造方法
     */
    public function __construct(
        \Api\Member\AuthManager\Auth           $Auth,
        \Api\Member\AuthManager\Models\Manager $Model,
        \Api\Member\AuthManager\Models\RoleManager $RoleManagerModel,
        \Api\Member\AuthPermissionRule\Models\Permission $PermissionModel,
        \Api\Member\AuthPermissionRule\Models\PermissionRule $PermissionRuleModel,
        LogRepository                          $LogRepository
    ) {
        $this->Auth   = $Auth;
        $this->Models = compact('Model', 'RoleManagerModel', 'PermissionModel', 'PermissionRuleModel');
        $this->LogRepository = $LogRepository;
    }

    /**
     * 获取当前账号信息
     * 
     * @return object
     * 
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function getSelf()
    {
        $self = $this->Model->findOrFail($this->Auth->id, [
            'id',
            'account',
            'country_code',
            'mobile',
            'last_ip',
            'status',
            'roles',
            'auth_fail_num',
            'confine_time',
            'created_at',
        ])->toArray();
        $authRules = [];
        if ($self['roles'] == 1){
            $authRules = ['admin'];
        }else{
            $role_ids = $this->RoleManagerModel->where('manager_id',$self['id'])->pluck('role_id')->toArray();
            if ($role_ids){
                $permission_rule_ids = $this->PermissionModel->whereIn('role_id',$role_ids)
                    ->select(['permission_rule_id'])
                    ->get()
                    ->toArray();
                foreach ($permission_rule_ids as $key=>$val){
                    $name = $this->PermissionRuleModel->where('id',$val['permission_rule_id'])->value('name');
                    if ($name){
                        $authRules[] = $name;
                    }
                }
            }
        }
        $self['authRules'] = $authRules;
        return $self;
    }

    /**
     * 修改登录密码（注意：前端明文密码需自行加密，防止传输过程中被抓包）
     * 
     * @param  string $oldPassword 旧密码
     * @param  string $nowPassword 新密码
     * @return void
     * 
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     * @throws \Member\AuthManager\Exceptions\Exception
     */
    public function changePassword($oldPassword, $nowPassword)
    {
        $manager = $this->getSelf();

        // 比对旧密码
        if (! app('hash')->check($oldPassword, $manager->password)) {
            throw_exception('Member\AuthManager', 'ChangePasswordFail', '原始密码错误');
        }

        // 写入数据
        $manager->password = $nowPassword;
        $manager->saveOrFail();

        // 记录日志
        $this->LogRepository->make('修改登录密码');
    }

    /**
     * 获取资源列表
     *
     * @param array $needColumns
     * @param array $where
     * @param int $needPerPage
     * @param array $orderBy
     * @return array
     */
    public function pageList(array $needColumns = ['id'], array $where = [], int $needPerPage = 10, array $orderBy = ['id', 'desc'])
    {
        // 常规查询
        $list = $this->_pageList($needColumns, $where, $needPerPage, $orderBy);
        foreach ($list['data'] as $key => &$value) {
            $roles = $this->RoleManagerModel->where('manager_id', $value['id'])->select('role_id')->get();
            $temp_roles = [];
            if ($roles){
                $temp_roles = $roles->toArray();
                $temp_roles = array_column($temp_roles,'role_id');
            }
            $value['roles'] = $temp_roles;
        }
        return $list;
    }

    /**
     * 获取资源列表 的 条件查询支持
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     * @param array $where
     * @return void
     */
    protected function makeListWhere(&$model, array $where = [])
    {
        $model = $model->where($where);
    }

    // 添加管理员
    public function managerAdd($data)
    {
        // 加锁操作
        DB::beginTransaction();
        $model = $this->Model;
        $model->account = $data['account'];
        $model->country_code = $data['country_code'];
        $model->mobile = $data['mobile'];
        $model->status = $data['status'];
        // 写入数据
        $model->saveOrFail();
        if ($data['roles']){
            $temp = [];
            foreach ($data['roles'] as $key => $value){
                $temp[$key]['role_id'] = $value;
                $temp[$key]['manager_id'] = $model->id;
            }
            //添加用户的角色
            $authRoleAdmin = $this->RoleManagerModel;
            $authRoleAdmin->insert($temp);
        }
        // 事务提交
        DB::commit();
    }

    // 编辑管理员
    public function managerEdit($managerId, $data)
    {
        // 加锁操作
        DB::beginTransaction();
        $model = $this->Model;
        $manager = $model->find($managerId);
        if (! $manager) {
            throw_exception('Member\AuthManager', 'DeleteFail', '管理员不存在');
        }
        $manager->account = $data['account'];
        $manager->country_code = $data['country_code'];
        $manager->mobile = $data['mobile'];
        $manager->status = $data['status'];
        // 写入数据
        $manager->saveOrFail();

        if ($data['roles']){
            // 先删除
            $this->RoleManagerModel->where('manager_id',$managerId)->delete();
            $temp = [];
            foreach ($data['roles'] as $key => $value){
                $temp[$key]['role_id'] = $value;
                $temp[$key]['manager_id'] = $managerId;
            }
            //添加用户的角色
            $authRoleAdmin = $this->RoleManagerModel;
            $authRoleAdmin->insert($temp);
        }
        // 事务提交
        DB::commit();
    }

    // 删除管理员
    public function managerDelete($managerId)
    {
        $manager = $this->Model->findOrFail($managerId);
        if ($manager->roles == 1) {
            throw_exception('Member\AuthManager', 'DeleteFail', '该管理员不能删除');
        }
        $manager->delete();
    }

}
